package com.eipv.multidatasource.controller;

import com.eipv.component.core.response.ResponseResult;
import com.eipv.component.mybatis.base.controller.BaseController;
import com.eipv.multidatasource.component.cache.PoolCache;
import com.eipv.multidatasource.component.cache.TableCache;
import com.eipv.multidatasource.service.LoadInService;
import com.eipv.multidatasource.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/monitor")
public class MonitorController extends BaseController {

    @Autowired
    private TableService tableService;
    @Autowired
    private LoadInService loadInService;

    /**
     * 页面请求
     */
    @GetMapping("/overview.html")
    public ModelAndView overview() {
        ModelAndView mav = new ModelAndView("monitor/monitor_overview");

        mav.addObject("isStarted", PoolCache.isStarted());
        mav.addObject("isLoading", PoolCache.isLoading());
        mav.addObject("initFinished", TableCache.INIT_FINISHED);
        mav.addObject("tables", TableCache.TABLES_OF_NEED_MIGRATE);
        return mav;
    }

    @GetMapping("/start.do")
    public ResponseResult.Response start() {
        if (PoolCache.isStarted()) {
            return this.failed("线程池已经在运行状态");
        } else {
            CompletableFuture.runAsync(tableService);
        }
        return this.success("启动成功");
    }

    @GetMapping("/loading.do")
    public ResponseResult.Response loading() {
        if (PoolCache.isLoading()) {
            return this.failed("已经处于数据迁移中");
        } else {
            CompletableFuture.runAsync(loadInService);
        }
        return this.success("启动成功");
    }

}
